const express = require('express')
const app = express();
const mkdirp = require('mkdirp')
const multer = require('multer')
const path = require('path')
const storage = multer.diskStorage({
    destination: async (req, file, cb) => { // 指定上传后保存到哪一个文件夹中
        let folder = (req.body && req.body.folder) || "unknown"; // 获取文件夹
        await mkdirp(`./uploaded/${folder}`);  // 创建目录
        cb(null, `./uploaded/${folder}`); //
    },
    filename: (req, file, cb) => { // 给保存的文件命名
        let extname = path.extname(file.originalname); // 获取后缀名
        cb(null, `${Date.now()}${extname}`);
    }
})
const upload = multer({ storage })
const HOST = "//img.moyv.top/" // 当前主域名
//const HOST = "//localhost:7171/" // 当前主域名
const PORT = "7171" //当前端口

// 托管静态文件
app.use("/uploaded", express.static(path.join(__dirname, './uploaded')));

// 跨域
app.all("*", function (req, res, next) {
    res.header('Access-Control-Allow-Origin', req.headers.origin);
    res.header('Access-Control-Allow-Methods', 'GET,PUT,POST,DELETE,OPTIONS');
    res.header('Access-Control-Allow-Headers', 'Content-Type');
    res.header('Access-Control-Allow-Credentials', 'true');
    next();
})

// 上传文件
app.post('/upload', upload.single('img'), function (req, res) {
    let folder = (req.body && req.body.folder) || "unknown"; // 获取文件夹
    // 给前端返回的数据
    res.send({
        Url: `${HOST}uploaded/${folder}/${req.file.filename}`,
        Filename: `${req.file.filename}`
    });
})

app.listen(PORT, () => console.log(`img upload 服务启动`));